# encoding: utf-8
"""
@author: 夏洛
@QQ: 1972386194
@file: 汽车.py
"""
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# http://chromedriver.storage.googleapis.com/index.html
import time

class CssOffset:
    def __init__(self):
        """初始化驱动"""
        option = webdriver.ChromeOptions()
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        option.add_argument('--disable-blink-features=AutomationControlled')
        self.driver = webdriver.Chrome(options=option)
        self.url = 'https://flight.qunar.com/site/oneway_list.htm?searchDepartureAirport=%E9%95%BF%E6%B2%99&searchArrivalAirport=%E6%B5%B7%E5%8F%A3&searchDepartureTime=2022-07-06&searchArrivalTime=2022-07-07&nextNDays=0&startSearch=true&fromCode=CSX&toCode=HAK&from=qunarindex&lowestPrice=null'
        self.wait = WebDriverWait(self.driver, 10)

    def get_flight_data(self):
        """获取机票数据"""
        script = "Object.defineProperty(navigator, 'webdriver', {get: () => false,});"
        self.driver.get(self.url)
        self.driver.execute_script(script)

        btn = self.driver.find_element_by_xpath('//div[@class="btn-box"]/div[@class="btn"]')
        btn.click()  # 点击确认
        time.sleep(1)

        divs = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="mb-10"]/div/div')))
        # divs = self.driver.find_elements_by_xpath('//div[@class="m-airfly-lst"]/div')
        return self.parse_line_data(divs)

    def parse_line_data(self, divs):
        """解析每条数据"""
        for div in divs:
            flight_name = div.find_element_by_xpath('.//div[@class="air"]').text   # 机场
            begin_time = div.find_element_by_xpath('.//div[@class="sep-lf"]/h2').text  # 开始时间
            end_time = div.find_element_by_xpath('.//div[@class="sep-rt"]/h2').text   # 结束时间
            prices = div.find_elements_by_xpath('.//div[@class="col-price"]//em[@class="rel"]/b/i')  # 定位占位价格
            price = [price.text for price in prices]
            to_cover_prices = div.find_elements_by_xpath('.//div[@class="col-price"]//em[@class="rel"]/b')  # 定位补坑的
            to_cover_prices_and_styles = [
                (to_cover_price.text, to_cover_price.get_attribute('style')) for to_cover_price in to_cover_prices[1:]
            ]
            true_price = self.replace_price(price, to_cover_prices_and_styles)    # 休整价格
            yield [flight_name, f'{begin_time}-{end_time}', true_price]

    def __del__(self):
        # 销毁资源
        self.driver.close()

    @staticmethod
    def replace_price(price, to_cover_prices_and_styles):
        """将价格进行恢复"""
        for to_cover_price, to_cover_style in to_cover_prices_and_styles:
            left = re.search('width: 16px; left: -(\d+)px;', to_cover_style).group(1)  # 提取偏移距离
            price[-int(left) // 16] = to_cover_price
        return ''.join(price)

if __name__ == '__main__':
    css_offset = CssOffset()
    for line in css_offset.get_flight_data():
        print(line)
